<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\common\model\printmanager\Goods as GoodsModel;
use app\common\model\printmanager\Comment;
use app\common\model\printmanager\Category as Category;
use think\Db;
use think\Config;
use fast\Random;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['goodsList', 'goodsInfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => '123']);
    }

    /*
     * 商品列表
     */
    public function goodsList(){
        $category_id = input('category_id/d', 0);
        $where_goods['display'] = 1;
        $where_goods['store'] = ['gt', 0];
        if($category_id > 0){
            $where_goods['category_id'] = $category_id;
        }

        $field = 'id, name, introduce, price, unit, sale_num_show, gold_num, category_id, images';
        $order = 'id DESC';
        $goods_list = GoodsModel::where($where_goods)->field($field)->order($order)->paginate()
            ->each(function($item, $key){
                $item->file_list =  $item->file_list;
        });

        $this->success('商品列表', $goods_list);
    }

    /*
     * 商品信息
     */
    public function goodsInfo(){
        $goods_id = input('id/d', 0);
        if($goods_id <= 0){
            $this->error('商品参数有误');
        }
        $where['id'] = $goods_id;
        $goods_info = GoodsModel::where($where)->find();
        if(!$goods_info){
            $this->error('商品不存在');
        }
        if($goods_info['display'] != 1){
            $this->error('商品已下架');
        }

        $goods_info['file_list'] = $goods_info->file_list;

        $comment_count = Comment::where(array('goods_id'=>$goods_id))->count();
        $goods_info['comment_count'] = $comment_count;
        $comment_list = collection( Comment::where(array('goods_id'=>$goods_id))->limit(10)->select())->each(function($item){
            $item->user_info = $item->user_info;
        });
        $goods_info['comment_list'] = $comment_list;

        GoodsModel::where('id', $goods_info->id)->setInc('click_count');

        // 对输入的文本处理
        $goods_info['content'] = richTextAbsoluteUrl($goods_info['content']);
        $goods_info['allow_golds_amount'] = round($goods_info['gold_num']/config('site.rmb_rate'),2);

        $this->success('商品信息', $goods_info);

    }

    /**
     * 商品加入购物车
     */
    public function addToCart(){
        $goods_id = input('id/d', 0);
        if($goods_id <= 0){
            $this->error('商品参数有误');
        }
        $where['id'] = $goods_id;
        $goods_info = GoodsModel::where($where)->find();
        if(!$goods_info){
            $this->error('商品不存在');
        }
        if($goods_info['display'] != 1){
            $this->error('商品已下架');
        }
        if($goods_info['store'] < 1){
            $this->error('商品库存不足');
        }
        $user_id = $this->auth->getUserinfo()['id'];

        $cart_info = Db::name('self_cart')->field('id, num, price')->where(array('user_id'=>$user_id, 'goods_id'=>$goods_id))->find();
        $data = $this->request->post();
        unset($data['token']);
        unset($data['id']);
        
        if(!isset($data['num']) || $data['num'] < 1){
            $this->error('商品数量最小为1');
        }

        $data['num'] = intval($data['num']);

        if(!$cart_info){
            
            $data['user_id'] = $user_id;
            $data['price'] = $goods_info['price'];
            $data['is_select'] = 0;
            $data['createtime'] = time();
            $data['goods_id'] = $goods_id;

            $is_success = Db::name('self_cart')->insertGetId($data);
            if($is_success){
                // GoodsModel::where($where)->setDec('store', $data['num'] );
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }

        }else{
            $data_update['num'] = $cart_info['num'] + $data['num'];
            $data_update['is_select'] = 0;
            $data_update['price'] = $goods_info['price'];
            $data_update['createtime'] = time();
            $is_success = Db::name('self_cart')->where(array('id'=>$cart_info['id']))->update($data_update);
            if($is_success === false){
                // GoodsModel::where($where)->setDec('store', $data['num'] );
                $this->error('添加失败');
            }else{
                $this->success('添加成功');
            }
        }
    }

    /*
     * 购物车列表
     */
    public function cartList(){

        $where['user_id'] = $this->auth->id;
        //第一次查询清理失效商品
        $cart_list = Db::name('self_cart')->where($where)->select();
        foreach($cart_list as $key => $val){
            $goods_info = GoodsModel::where(array('id'=>$val['goods_id']))->find();
            if(!$goods_info || $goods_info['display'] == 0 || $goods_info['store'] == 0){
                Db::name('self_cart')->where(array('id'=>$val['id']))->delete();
            }else if($goods_info['price'] != $val['price']){
                Db::name('self_cart')->where(array('id'=>$val['id']))->update(array('price'=>$goods_info['price']));
            }
        }
            
        $cart_list = collection(Db::name('self_cart')->where($where)->select())->each(function($item){
            $goods_info =  GoodsModel::where(array('id'=>$item['goods_id']))->find();
            $goods_info->file_list = $goods_info->file_list;
            $item['goods_info'] = $goods_info;
            return $item;
        });

        $this->success('购物车列表', $cart_list);
    }

    /*
     * 编辑购物车商品数量
     */
    public function editCart(){
       
        $where['user_id'] = $this->auth->id;
        
        if($this->request->has('all')){
            $all = input('all/d', 0);
            $update = ['is_select' => $all];
            $is_success = Db::name('self_cart')->where($where)->update($update);
        }else{
            $id = input('id/d', 0);
            $where['id'] = $id;
            $cart_info = Db::name('self_cart')->field('id,goods_id, is_select,num, price')->where($where)->find();
            if(!$cart_info){
                $this->error('购物车参数有误');
            }
    
            $num = input('num/d', 1);
            $is_select = input('is_select/d', 1);
    
            if($num < 1){
                $this->error('商品数量最小为1');
            }
    
            $is_success = Db::name('self_cart')->where(array('id'=>$cart_info['id']))->update(array(
                'num' => $num,
                'is_select' =>$is_select,
            ));

            // if($is_success){
            //     $dirt = $num - $cart_info['num'];
            //     if($dirt != 0)
            //     GoodsModel::where('id', $cart_info['goods_id'])->setDec('store', $num );
            // }
        }

        if($is_success !== false){
            $this->success('操作成功'); 
        }else{
            $this->error('操作失败');
        }
        
    }

    /*
     * 删除
     */
    public function delCart(){
        $ids = input('ids/a', []);
        if(empty($ids)){
            $this->error('请选择要删除的商品');
        }
        $where['user_id'] = $this->auth->id;
        $where['id'] = ['in', $ids];

        $cart_info = Db::name('self_cart')->field('id,goods_id, is_select,num, price')->where($where)->find();
        if(!$cart_info){
            $this->error('购物车参数有误');
        }

        $res = Db::name('self_cart')->where($where)->delete();
        if($res===false){
            $this->error('删除失败');
        }

        // GoodsModel::where('id', $cart_info['goods_id'])->setInc('store', $cart_info['num'] );
         
        $this->cartList();
    }
}